﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TopVidionApplication;
using TopVisionLog;
using TopVisionVideoStream;
using VideoStream.Common;
using VideoStream.Model;

namespace VideoStream.Windows
{
    public partial class Windows_ImageDraw : VideoStream.Windows.WindowsBase
    {
        private Control target;
        private Image image;
        private Point newLocation = Point.Empty;
        private Size newSize = Size.Empty;
        private DrawTools dt;
        private Point drawPoint = Point.Empty;
        private bool sendMark = false;

        private SaveFileDialog saveFileDialog = new SaveFileDialog();

        public bool SendMark
        {
            get { return sendMark; }
            set { sendMark = value; }
        }

        public Windows_ImageDraw(Control target, Image image)
        {
            this.target = target;
            this.image = image;
            if (Windows_Main.Instance.WinDisplay.IsPhoto)
            {
                Bitmap bmp = new Bitmap(this.image, target.Size);
                this.image = bmp;
            }
            InitializeComponent();
            InitUI();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            InitEvent();
            UpdateUI();
            CreateCanvas();
        }

        protected override void OnClosed(EventArgs e)
        {
            dt.ClearVar();
            UnRegistEvent();
            base.OnClosed(e);
        }

        public override void InitUI()
        {
            base.InitUI();

            this.ShowInTaskbar = false;
            this.showBorder = false;

            pic_Image.BackColor = Color.Black;
            pic_Image.BackgroundImageLayout = ImageLayout.Zoom;
            pic_Image.BackgroundImage = this.image;

            //saveFileDialog.AutoUpgradeEnabled = false;
            saveFileDialog.Filter = "Jpeg(*.jpg)|*.jpg";
            saveFileDialog.RestoreDirectory = true;

            if (ApplicationData.markType != 0) MarkOption.GeoType = ApplicationData.markType;
            if (!string.IsNullOrEmpty(ApplicationData.markColor)) MarkOption.ColorType = ApplicationData.markColor;
            if (ApplicationData.markSolid != 0) MarkOption.SolidType = ApplicationData.markSolid;

            SendMark = Windows_Main.Instance.WinDisplay.IsPhoto;
        }
        public override void InitEvent()
        {
            base.InitEvent();

            RegistEvent();

        }
        public override void UpdateUI()
        {
            base.UpdateUI();

            UpdateSize();
            UpdateLocation();

            panel_Process.Hide();
            btn_Save._Text = TVString.STR_Save;
            btn_Close._Text = TVString.STR_Back;
            this.BackColor = TVColor.Color_DarkBlack;
        }

        private void RegistEvent()
        {
            if (Windows_Main.Instance != null)
            {
                if (!Windows_Main.Instance.IsDisposed)
                {
                    Windows_Main.Instance.LocationChanged += Instance_LocationChanged;
                }

            }
            if (target != null)
            {
                if (!target.IsDisposed)
                {
                    target.SizeChanged += Target_SizeChanged;
                    target.Disposed += Target_Disposed;
                    Windows_Main.Instance.WinDisplay.VisibleChanged += Target_VisibleChanged;
                }
            }


            MarkOption.Click += MarkOption_Click;
            MarkOption.ClearClick += MarkOption_ClearClick;

            pic_Image.MouseDown += Target_MouseDown;
            pic_Image.MouseMove += Target_MouseMove;
            pic_Image.MouseUp += Target_MouseUp;

            btn_Save.Click += Btn_Save_Click;
            btn_Close.Click += Btn_Close_Click;

            panel_Process.Paint += Panel_Process_Paint;

            this.VisibleChanged += Windows_ImageDraw_VisibleChanged;
        }

        private void Panel_Process_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Pen p = new Pen(TVColor.Color_HighLight, 1);
            g.DrawRectangle(p, 0, 0, panel_Process.Width - p.Width, panel_Process.Height - p.Width);
        }

        private void UnRegistEvent()
        {
            if (Windows_Main.Instance != null)
            {
                if (!Windows_Main.Instance.IsDisposed)
                {
                    Windows_Main.Instance.LocationChanged -= Instance_LocationChanged;
                }

            }
            if (target != null)
            {
                if (!target.IsDisposed)
                {
                    target.SizeChanged -= Target_SizeChanged;
                    target.Disposed -= Target_Disposed;
                    Windows_Main.Instance.WinDisplay.VisibleChanged -= Target_VisibleChanged;
                }
            }


            MarkOption.Click -= MarkOption_Click;
            MarkOption.ClearClick -= MarkOption_ClearClick;

            pic_Image.MouseDown -= Target_MouseDown;
            pic_Image.MouseMove -= Target_MouseMove;
            pic_Image.MouseUp -= Target_MouseUp;

            btn_Save.Click -= Btn_Save_Click;
            btn_Close.Click -= Btn_Close_Click;

            panel_Process.Paint -= Panel_Process_Paint;
        }

        private void UpdateSize()
        {
            newSize = this.target.Size;
            this.Size = newSize;
        }
        private void UpdateLocation()
        {
            newLocation = target.PointToScreen(Point.Empty);
            this.Location = newLocation;
        }

        private void Windows_ImageDraw_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                if (!this.IsDisposed)
                {
                    UpdateCanvas(100);
                }
            }
        }

        private void Target_VisibleChanged(object sender, EventArgs e)
        {
            if (target != null)
            {
                if (!target.IsDisposed)
                {
                    this.Visible = target.Visible;
                }
            }
        }

        private void Target_Disposed(object sender, EventArgs e)
        {
            UnRegistEvent();
            Hide();
            Close();
        }

        private void Instance_LocationChanged(object sender, EventArgs e)
        {
            UpdateLocation();
        }

        private void Target_SizeChanged(object sender, EventArgs e)
        {
            UpdateSize();
        }

        private void CreateCanvas()
        {
            dt = new DrawTools(pic_Image.CreateGraphics(), TransparencyKey, (Image)this.image.Clone());
            //dt = new DrawTools(Graphics.FromImage(pic_Image.BackgroundImage), this.TransparencyKey, (Image)this.image.Clone());
        }

        private void Target_MouseUp(object sender, MouseEventArgs e)
        {
            if (dt.startDraw)
            {
                dt.startDraw = false;
                dt.EndDraw();
                if (SendMark)
                {
                    drawPoint = e.Location;
                    int width = this.Width;
                    int height = this.Height;
                    int sX = dt.startPointF.X;
                    int sY = dt.startPointF.Y;
                    int eX = drawPoint.X;
                    int eY = drawPoint.Y;
                    int pT = MarkOption.GeoType;
                    string cT = MarkOption.ColorType;
                    int pWidth = MarkOption.SolidType;

                    TVVS.Features_Mark(width, height, sX, sY, eX, eY, pT, cT, pWidth);
                }
            }
        }

        private void Target_MouseMove(object sender, MouseEventArgs e)
        {
            if (dt.startDraw)
            {
                drawPoint = e.Location;
                string t = "Rect";
                switch (MarkOption.GeoType)
                {
                    case 3:
                        t = "Rect";
                        break;
                    case 5:
                        t = "Circle";
                        break;
                    case 10:
                        t = "Line";
                        break;
                    default:
                        break;
                }
                dt.Draw(drawPoint, t);
                // t
                //pic_Image.BackgroundImage = dt.OrginalImg;
            }
        }

        private void Target_MouseDown(object sender, MouseEventArgs e)
        {
            dt.startDraw = true;
            drawPoint = e.Location;
            dt.startPointF.X = drawPoint.X;
            dt.startPointF.Y = drawPoint.Y;
            dt.DrawColor = ColorTranslator.FromHtml(MarkOption.ColorType);
            dt.Solid = MarkOption.SolidType;
        }

        private void Btn_Close_Click(object sender, EventArgs e)
        {
            if (Windows_Main.Instance.WinDisplay.IsSrcShot)
                Windows_Main.Instance.WinDisplay.QuitSrcShot();
            if (Windows_Main.Instance.WinDisplay.IsPhoto)
                Windows_Main.Instance.WinDisplay.QuitPhoto();
        }

        private void Btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = "srcshot" + CommonFun.GetTimeSnap() + ".jpg";
                saveFileDialog.FileName = fileName;
                var ret = saveFileDialog.ShowDialog(this);

                if (ret == DialogResult.OK)
                {
                    if (File.Exists(saveFileDialog.FileName))
                    {
                        File.Delete(saveFileDialog.FileName);
                    }

                    dt.OrginalImg.Save(saveFileDialog.FileName, ImageFormat.Jpeg);

                    Windows_MessageBox wmb = new Windows_MessageBox(string.Format(TVString.STR_F_ImageSavedSend, fileName), MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    wmb.SetConfirmText(TVString.STR_Send);
                    var sd = wmb.ShowDialog(this);
                    if (sd == DialogResult.OK)
                    {
                        btn_UpClose._Text = TVString.STR_Cancel;
                        bar_Upload.Value = 0;
                        lab_FileName.Text = "";
                        lab_UpData.Text = "0/0";
                        lab_UpPersent.Text = "0%";
                        UploadInfo upInfo = new UploadInfo(saveFileDialog.FileName);
                        upInfo.OnProgressing += (o) =>
                        {
                            lab_FileName.Text = o.FileName;
                            lab_UpData.Text = o.BytesSend + " / " + o.TotalBytesToSend;
                            lab_UpPersent.Text = o.ProgressPercentage + "%";
                            bar_Upload.Value = o.ProgressPercentage;
                        };
                        upInfo.OnCompleted += (o) =>
                        {
                            //string _url = string.Format("{0}/{1}/{2}/{3}/{4}{5}", HttpAPI.baseUrl, "topvisionupload", "videostream", CommonFun.currentUser, "photo", _name);
                            int _s = o.data.LastIndexOf("/");
                            string _name = o.data.Substring(_s);
                            btn_UpClose._Text = TVString.STR_Complete;
                            string imgUrl = string.Format("{0}/{1}/{2}/{3}/{4}{5}", HttpAPI.baseUrl, "topvisionupload", "videostream", ApplicationData.Account, "photo", _name);
                            Console.WriteLine("Img url : " + imgUrl);
                            string msg = string.Format("图片地址,{0}", imgUrl);
                            TVVS.Features_SendMessage(msg);
                            Console.WriteLine(msg);
                        };
                        btn_UpClose._Text = TVString.STR_Cancel;
                        btn_UpClose.Click += Btn_Upload_Close;
                        btn_UpClose.Tag = upInfo;
                        panel_Process.Show();
                        upInfo.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                Windows_MessageBox wmb = new Windows_MessageBox(TVString.STR_Save + TVString.STR_Failed, MessageBoxButtons.OK, MessageBoxIcon.Error);
                wmb.ShowDialog(this);
                TVLog.WriteLine("save screenshot error :" + ex.Message);
                Console.WriteLine("save screenshot error :" + ex.Message);
            }
        }

        private void Btn_Upload_Close(object sender, EventArgs e)
        {
            btn_UpClose.Click -= Btn_Upload_Close;
            UploadInfo upInfo = btn_UpClose.Tag as UploadInfo;
            upInfo.Stop();
            panel_Process.Hide();
        }

        private void MarkOption_Click(object sender, EventArgs e)
        {
            ApplicationData.markType = MarkOption.GeoType;
            ApplicationData.markColor = MarkOption.ColorType;
            ApplicationData.markSolid = MarkOption.SolidType;
        }

        private void MarkOption_ClearClick(object sender, EventArgs e)
        {
            pic_Image.BackColor = Color.Black;
            Graphics g = pic_Image.CreateGraphics();
            g.FillRectangle(new SolidBrush(this.TransparencyKey), 0, 0, target.Width, target.Height);
            g.Dispose();
            pic_Image.Hide();
            pic_Image.Show();
            pic_Image.BackgroundImage = this.image;
            CreateCanvas();
            TVVS.Features_ClearMark();
        }

        private async void UpdateCanvas(int delay = 100)
        {
            await Task.Delay(delay);
            //Graphics g = this.CreateGraphics();
            //g.DrawImage(dt.CurImage, 0, 0);

            pic_Image.BackgroundImage = dt.OrginalImg;
        }

    }
}
